
import { _decorator, Component, Node, Vec3, RigidBody2D, Animation, labelAssembler } from 'cc';
const { ccclass, property } = _decorator;

enum Status{
    fly = 1,
    die
}

@ccclass('birdControl')
export class birdControl extends Component {
    // 生命值
    hp: number = 1;
    // 目标位置 x:+-400 y:410
    targetPos: Vec3 = null;
    // 速度
    @property
    speed: number = 50;

    width: number;
    height: number;

    //状态
    status: number;

    // 游戏结束回调
    dieCallBack: Function;
    // 加分回调
    addScoreCallBack: Function;

    start () {
        this.status = Status.fly;
        // 随机目标点
        this.targetPos = new Vec3(Math.random() * 800 - 400, 410, 0);
        //console.log(this.targetPos.x, this.targetPos.y);
        // 旋转精灵
        if(this.targetPos.x > this.node.position.x){
            this.node.setScale(-2,2,1);
            this.node.setRotation(0,0,-50,0);
        }
        // 获取直角三角形直角两边的长度
        if(this.targetPos.x > this.node.position.x){
            this.width = -(this.targetPos.x - this.node.position.x)/this.speed;
        }else{
            this.width = (this.node.position.x - this.targetPos.x)/this.speed;
        }
        this.height = (this.targetPos.y - this.node.position.y)/this.speed;
    }

    fly(){
        // 移动
        let rb = this.getComponent(RigidBody2D);
        let lv = rb.linearVelocity;
        lv.x = this.width; 
        lv.y = this.height;
        rb.linearVelocity = lv;
        // 飞出界面
        if(this.node.position.y > 620 || (this.node.position.x < -510 || this.node.position.x > 510)){
            console.log(this.node.position.x, this.node.position.y);
            this.dieCallBack();
        }
    }

    fall(){
        // 移动
        let rb = this.getComponent(RigidBody2D);
        let lv = rb.linearVelocity;
        lv.y = -30;
        rb.linearVelocity = lv;
        // 掉落地面
        if(this.node.position.y < - 300) {
            this.node.destroy();
        }
    }

    update (deltaTime: number) {
        if(this.status === Status.fly) this.fly();
        else this.fall();
        // 触摸精灵
        this.node.on(Node.EventType.TOUCH_START, (event) => {
            // 减少血量
            if(this.hp > 0){
                this.status = Status.die;
                this.hp --;
                // 播放动画
                this.getComponent(Animation).play('die');
                // 得分
                this.addScoreCallBack();
            }
        });
    }
}